package com.regiee.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/*
全局异常处理器
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})//处理哪里的异常
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)//捕获这个类型的异常
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
        log.error(exception.getMessage());//抛出的异常信息
        //根据抛出的异常的信息来判断是哪种错误
        if(exception.getMessage().contains("Duplicate entry")){
            String[] split=exception.getMessage().split(" ");
            String msg=split[2]+"已经存在了";
            return R.error(msg);
        }
        return R.error("未知的错误");
    }
    @ExceptionHandler(CustomException.class)//捕获这个类型的异常
    public R<String> exceptionHandler(CustomException exception){
        log.error(exception.getMessage());//抛出的异常信息
        //根据抛出的异常的信息来判断是哪种错误
        return R.error(exception.getMessage());
    }
}
